import { save_local_history } from '../tauriApi';
import { useTimelineStore } from '../stores/timeline';

// Debouncing to prevent excessive saves
let saveDebounceTimer: any = null;
const saveDebounceMap = new Map<string, any>();

// Function to add local history snapshot when file is actually saved
export async function addLocalHistorySnapshot(filePath: string, content: string) {
    // Clear any existing timer for this file
    if (saveDebounceMap.has(filePath)) {
        clearTimeout(saveDebounceMap.get(filePath));
    }

    // Set up debounced save (300ms delay)
    const timer = setTimeout(async () => {
        const timelineStore = useTimelineStore();
        try {
            await save_local_history(filePath, content);
            // Refresh timeline after saving history (also debounced)
            await timelineStore.refreshTimeline();
        } catch (e) {
            console.warn('Could not save local history', e);
        } finally {
            saveDebounceMap.delete(filePath);
        }
    }, 300);

    saveDebounceMap.set(filePath, timer);
}

// Legacy function for backward compatibility
export function setupLocalHistory() {
    // This function is now empty as we handle history saving
    // directly in the save functions in EditorArea.vue
}